package com.authine.cloudpivot.ext.applicationservice;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapBuilder;
import cn.hutool.core.map.MapUtil;
import com.alibaba.cola.dto.RequestContext;
import com.alibaba.cola.dto.SingleResponse;
import com.alibaba.fastjson.JSON;
import com.authine.cloudpivot.ext.constants.AppConst;
import com.authine.cloudpivot.ext.constants.ModelConst;
import com.authine.cloudpivot.ext.domain.dto.CartBatchDto;
import com.authine.cloudpivot.ext.domain.dto.DemandGoodsToInquiryDto;
import com.authine.cloudpivot.ext.domain.dto.base.Ids;
import com.authine.cloudpivot.ext.enums.CartSrcEnum;
import com.authine.cloudpivot.ext.enums.commoditymaterials.GoodsPurchaseTypeEnum;
import com.authine.cloudpivot.ext.enums.order.CartTypeEnum;
import com.authine.cloudpivot.ext.enums.order.GoodsSrcEnum;
import com.authine.cloudpivot.ext.enums.order.OrderVendorStatusEnum;
import com.authine.cloudpivot.ext.service.OrderService;
import com.authine.cloudpivot.ext.service.impl.OrderServiceImpl;
import com.authine.cloudpivot.ext.utils.*;
import com.authine.common.json.JsonUtils;
import com.authine.common.util.DateUtils;
import com.authine.hermes.app.launcher.service.ApplicationService;
import com.authine.mvp.app.launcher.domain.AddrFormat;
import com.authine.mvp.app.launcher.domain.SelectorFormat;
import com.authine.mvp.app.launcher.domain.utills.ApplicationContextUtils;
import com.authine.mvp.app.launcher.dto.bo.response.BO;
import com.authine.mvp.app.launcher.gateway.bo.BOValidatedAndFormatService;
import com.authine.mvp.app.org.dto.domainmodel.UnitType;
import io.swagger.v3.oas.annotations.Operation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.util.CollectionUtils;

import javax.ws.rs.POST;
import javax.ws.rs.Path;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import static com.authine.hermes.app.launcher.service.ApplicationServiceFoundation.CUSTOM_SERVICE;

@Path("ShoppingCartService")
@Slf4j
public class ShoppingCartService extends ApplicationService {
    private OrderService orderService = OrderServiceImpl.getInstance();
    NamedParameterJdbcTemplate jdbcTemplate = ApplicationContextUtils.getBean(NamedParameterJdbcTemplate.class);
    BOValidatedAndFormatService bOValidatedAndFormatService = ApplicationContextUtils.getBean(BOValidatedAndFormatService.class);

    /**
     * 先加入再获取生成订单数据
     *
     * @return
     */
    @Path("joinWholeOrder")
    @POST
    @Operation(summary = "购物车-整单加入", tags = CUSTOM_SERVICE, description = "InquiryId:Array,goodsSrc:str")
    public SingleResponse joinWholeOrder(CartBatchDto dto){

        if (StringUtils.isEmpty(dto.getInquiryId())) {
            return SingleResponse.buildFailure("-1", "询价单id 不能为空");
        }


        List<Map<String, Object>> goodsPurchase = JdbcTemplateUtils.builder(ModelConst.T_GOODS_PURCHASE)
                .selectField(" * ")
                .eq("inquiry_id", dto.getInquiryId())
                .queryForList();


        for (Map<String, Object> goods : goodsPurchase) {
            List<Map<String, Object>> cart = JdbcTemplateUtils.builder(AppConst.COMMODITYMATERIALS, ModelConst.T_CART)
                    .selectField(" * ")
                    .eq("goods_id", goods.get("id"))
                    .queryForList();


            if (null == cart || cart.isEmpty()) {

                SingleResponse<BO> rst = doCreateCart(goods, goods.get("num"));

                if (!rst.isSuccess()) {
                    return rst;
                }
            }
        }

        List<String> cartIds = JdbcTemplateUtils.builder(ModelConst.T_CART)
                .selectField(" id ")
                .in("goods_id", goodsPurchase.stream().map(a -> a.get("id")).collect(Collectors.toList()))
                .queryForList(String.class);

        if (cartIds == null || cartIds.isEmpty()) {
            return SingleResponse.buildFailure("-1", "整单加入购物车失败");
        }


        return SingleResponse.of(cartIds.stream().collect(Collectors.joining(",")));
    }


    private SingleResponse<BO> doCreateCart(Map<String, Object> purchaseData, Object num) {


        SelectorFormat member = new SelectorFormat();
        member.setType(UnitType.USER.getIndex());
        member.setName(RequestContext.getLoginRealName());
        member.setId(RequestContext.getCorpLoginId());

        SelectorFormat vendor_id = Utils.toSelectorFormat(purchaseData.get("vendor_id"));
        String vendorName = null;
        SelectorFormat customer_id = Utils.toSelectorFormat(purchaseData.get("customer_id"));
        String customerName = null;

        if (null != vendor_id) {
            vendorName = vendor_id.getName();
        }

        if (null != customer_id) {
            customerName = customer_id.getName();
        }

        Integer goodsSrc = String.valueOf(GoodsPurchaseTypeEnum.SINGLE.getId()).equals(String.valueOf(purchaseData.get("type"))) ? CartSrcEnum.SINGLE.id : CartSrcEnum.LOOP.id;

        MapBuilder<String, Object> cartMap = new MapBuilder(new HashMap<String, Object>());

        cartMap.put("type", CartTypeEnum.DIRECT.getId())
                .put("goods_src", goodsSrc)
                .put("enabled", "0".equals(String.valueOf(purchaseData.get("quote_total_strategy"))))
                .put("pretax_price", purchaseData.get("pretax_price"))
                .put("goods_id", purchaseData.get("id"))
                .put("brand", purchaseData.get("brand"))
                .put("name", purchaseData.get("name"))
                .put("model", purchaseData.get("model"))
                .put("spec", purchaseData.get("spec"))
                .put("images", purchaseData.get("images"))
                .put("unit", purchaseData.get("unit"))
                .put("quantity",  num)
                .put("package_unit", purchaseData.get("package_unit"))
                .put("package_quantity", purchaseData.get("package_num"))
                .put("warranty", purchaseData.get("warranty"))
                .put("delivery", purchaseData.get("delivery"))
                .put("tax_rate", purchaseData.get("tax_rate"))
                .put("price", purchaseData.get("price"))
                .put("freight", purchaseData.get("freight"))
                .put("total", purchaseData.get("total"))
                .put("amount", purchaseData.get("amount"))
                .put("enabled", "1".equals(purchaseData.get("enabled")))
                .put("maximum", purchaseData.get("maximum"))
                .put("min_order", purchaseData.get("min_order"))
                .put("member_id", member)
                .put("member_name", RequestContext.getLoginRealName())
                .put("customer_organization_id", customer_id)
                .put("customer_organization_name", customerName)
                .put("vendor_organization_id", vendor_id)
                .put("vendor_organization_name", vendorName)
                .put("extends_attr", purchaseData.get("suk"))
                .put("version", purchaseData.get("version"))
                .put("vendor_sku", purchaseData.get("vendor_sku"))
                .put("pretax_freight", purchaseData.get("pretax_freight"))
                .put("tax_payable_freight", purchaseData.get("tax_payable_freight"))
                .put("tax_payable_freight_tota", purchaseData.get("tax_payable_freight_tota"))
                .put("tax_rate_freight", purchaseData.get("tax_rate_freight"));

        Map<String, Object> map = cartPriceChange(cartMap.build());

        cartMap.putAll(map);

        bigDecimalScale(cartMap.map());

        log.info("===================cartMap={}", cartMap.build());
        SingleResponse<BO> rst = BoServiceUtils.createBo(ModelConst.T_CART, Collections.singletonList(cartMap.build()));
        log.info("===================rst={}", rst);

        return rst;
    }

    private void bigDecimalScale(final Map<String, Object> cartMap) {

        cartMap.entrySet().forEach(e -> {
            if (e.getValue() != null && e.getValue() instanceof BigDecimal) {
                //小数类型 保留 6位 当前版本(7.0.1)问题,必须这样处理
//                e.setValue(((BigDecimal) e.getValue()).setScale(6, RoundingMode.HALF_UP));

                if (((BigDecimal) e.getValue()).compareTo(BigDecimal.ZERO) == 0) {
                    // OE-16报错问题 当前版本(7.0.2)问题,必须这样处理
                    e.setValue(BigDecimal.ZERO);
                }

            }
        });
    }


    @Path("toCrateCart")
    @POST
    @Operation(summary = "购物车-生成购物车采购单数据", tags = CUSTOM_SERVICE, description = "id:string,num:int,goodsSrc:str")
    public SingleResponse toCrateCart(CartBatchDto dto) {

        if (StringUtils.isEmpty(dto.getPurchaseId())) {
            return SingleResponse.buildFailure("-1", "商品id 不能为空");
        }

        if (dto.getNum() == null || dto.getNum().intValue()<1 || 99999999 < dto.getNum().intValue()){
            return SingleResponse.buildFailure("-1","商品数量错误");
        }


        Map<String, Object> purchaseData = BoServiceUtils.loadBo(dto.getPurchaseId(), ModelConst.T_GOODS_PURCHASE).getData().getData();

        if (purchaseData.isEmpty()){
            return SingleResponse.buildFailure("-1","数据不存在");
        }


        if ( null == purchaseData.get("expire")  || new Date().after(DateUtil.parse( (String) purchaseData.get("expire"), DatePattern.NORM_DATETIME_PATTERN))) {
            return SingleResponse.buildFailure("-1","商品已失效");
        }

        if (!Utils.parseObjToBool(purchaseData.get("enabled"))) {
            return SingleResponse.buildFailure("-1","商品未启用");
        }

        //todo 购物车是否已存在
        List<Map<String, Object>> cart = BoServiceUtils.findListBySimple(ModelConst.T_CART, "goods_id", purchaseData.get("id")).getData().getData();

        // 购物车已存在,修改数量
        if (!cart.isEmpty()) {
            if (cart.get(0).get("goods_src") != null && CartSrcEnum.get(cart.get(0).get("goods_src")) == CartSrcEnum.SINGLE) {
                return SingleResponse.buildFailure("-2", "该商品购物车已存在");
            } else {
                dto.setId((String) cart.get(0).get("id"));
                return toUpdateNum(dto);
            }
        }


        SingleResponse rst = doCreateCart(purchaseData, dto.getNum());

        if (!rst.isSuccess()) {
            return SingleResponse.buildFailure("-1", "创建失败");
        }

        return SingleResponse.buildSuccess();
    }

    /**
     * 批量加入
     *
     * @return
     */
    @Path("batchAddCart")
    @POST
    @Operation(summary = "购物车-询价定标批量加入购物车", tags = CUSTOM_SERVICE, description = "id:string,num:int,goodsSrc:str")
    public SingleResponse batchAddCart(CartBatchDto dto) {

        List<Map<String, Object>> purchaseList = JdbcTemplateUtils.builder(ModelConst.T_GOODS_PURCHASE)
                .selectField(" id,expire,num,enabled ")
                .in("id", dto.getPurchaseIds())
                .queryForList();


        if (purchaseList.isEmpty()) {
            return SingleResponse.buildFailure("-1", "失败,商品不存在");

        }

        for (Map<String, Object> purchaseData : purchaseList) {

            if (null == purchaseData.get("expire") || new Date().after((Date) purchaseData.get("expire"))) {
                return SingleResponse.buildFailure("-1", "商品已失效");
            }

            if (!Utils.parseObjToBool(purchaseData.get("enabled"))) {
                return SingleResponse.buildFailure("-1", "商品未启用");
            }
        }

        List<String> goodsIds = JdbcTemplateUtils.builder(ModelConst.T_CART)
                .selectField(" goods_id  ")
                .in("goods_id", purchaseList.stream().map(a -> a.get("id")).collect(Collectors.toList()))
                .queryForList(String.class);

        if (goodsIds.size() > 0) {
            return SingleResponse.buildFailure("-1", String.format("序号%s商品在购物车中已存在请勿重复加入！", goodsIds.get(0)));
        }
        CartBatchDto cartDto;
        List<String> failList = new ArrayList<>();
        for (Map<String, Object> purchaseData : purchaseList) {
            cartDto = new CartBatchDto();

            cartDto.setNum((BigDecimal) purchaseData.get("num"));
            cartDto.setPurchaseId((String) purchaseData.get("id"));

            try {
                SingleResponse singleResponse = toCrateCart(cartDto);

                if (!singleResponse.isSuccess()) {
                    failList.add(cartDto.getPurchaseId());
                }

            } catch (Exception e) {
                failList.add(cartDto.getPurchaseId());
            }

        }

        if (failList.size() > 0) {
            return SingleResponse.buildFailure("-1", String.format("序号%s商品加入购物车失败", StringUtils.join(failList, ",")));
        }

        return SingleResponse.buildSuccess();
    }


    @Path("getCartCount")
    @POST
    @Operation(summary = "购物车-获取购物车采购单数量", tags = CUSTOM_SERVICE, description = "无")
    public SingleResponse getCartCount() {

        int count = JdbcTemplateUtils.builder(ModelConst.T_CART)
                .selectField("count(*) as count")
                .in("type", Arrays.asList(CartTypeEnum.DIRECT.getId(), CartTypeEnum.EnterpriseMall.getId()))
                .eq("member_id -> '$.id'", RequestContext.getCorpLoginId())
                .queryForObject(Integer.class);

        SingleResponse response = SingleResponse.buildSuccess();
        response.setData(count);

        return response;
    }


    @Path("toUpdateNum")
    @POST
    @Operation(summary = "购物车-修改采购单数量", tags = CUSTOM_SERVICE, description = "入参{id:string，num:int}")
    public SingleResponse toUpdateNum(CartBatchDto dto){

        if (StringUtils.isEmpty(dto.getId())) {
            return SingleResponse.buildFailure("-1", "id 不 能为空");
        }

        if (null != dto.getNum() &&
                (BigDecimal.ZERO.compareTo(dto.getNum())==1
                        || new BigDecimal(99999999).compareTo(dto.getNum())==-1 ))  {
            return SingleResponse.buildFailure("-1", "商品数量有误");
        }

        Map<String, Object> boData = BoServiceUtils.loadBo(dto.getId(), ModelConst.T_CART).getData().getData();

        if (boData.isEmpty()) {
            return SingleResponse.buildFailure("-1", "购物车数据不存在");
        }

        if (boData.get("goods_src") != null && CartSrcEnum.get(boData.get("goods_src")) == CartSrcEnum.SINGLE) {
            return SingleResponse.buildFailure("-2", "单次购买不能调整采购数量");
        }

        boData.put("quantity", dto.getNum());

        MapBuilder<String, Object> put = MapBuilder.create(new HashMap<String, Object>())
                .put("id", dto.getId())
                .putAll(cartPriceChange(boData));

        bigDecimalScale(put.map());

        SingleResponse<BO> response = BoServiceUtils.updateMainBo(ModelConst.T_CART, put.build());

        log.info("===============response={}", response);

        return SingleResponse.buildSuccess();
    }


    /**
     * 价格变动
     *
     * @param boData
     * @return
     */
    private Map<String, Object> cartPriceChange(Map<String, Object> boData) {
        //数量
        BigDecimal num = (BigDecimal) boData.get("quantity");
        //税前单价
        BigDecimal pretaxPrice = (BigDecimal) boData.get("pretax_price");
        //税前总价
        BigDecimal pretaxTotal = BigDecimalUtils.mul(pretaxPrice, num).setScale(16, BigDecimal.ROUND_HALF_UP);
        //税后单价
        BigDecimal price = (BigDecimal) boData.get("price");
        //税后总价
        BigDecimal total = BigDecimalUtils.mul(price, num).setScale(16, BigDecimal.ROUND_HALF_UP);
        //商品税额
        BigDecimal taxPayable = BigDecimalUtils.sub(total, pretaxTotal).setScale(16, BigDecimal.ROUND_HALF_UP);
        //税前运费
        BigDecimal pretaxFreight = (BigDecimal) boData.get("pretax_freight");
        //税前运费总价
        BigDecimal pretaxFreightTotal = BigDecimalUtils.mul(pretaxFreight, num).setScale(16, BigDecimal.ROUND_HALF_UP);
        //税后运费
        BigDecimal freight = (BigDecimal) boData.get("freight");
        //税后运费总价
        BigDecimal freightTotal = BigDecimalUtils.mul(freight, num).setScale(16, BigDecimal.ROUND_HALF_UP);
        //运费税额
        BigDecimal taxPayableFreightTotal = BigDecimalUtils.sub(freightTotal, pretaxFreightTotal).setScale(16, BigDecimal.ROUND_HALF_UP);
        //税前商品运费总计
        BigDecimal pretaxAmount = BigDecimalUtils.add(pretaxTotal, pretaxFreightTotal).setScale(16, BigDecimal.ROUND_HALF_UP);
        //税后商品运费共计
        BigDecimal amount = BigDecimalUtils.add(freightTotal, total).setScale(16, BigDecimal.ROUND_HALF_UP);


        return MapBuilder.create(new HashMap<String, Object>())
                .put("quantity", num)
                .put("pretax_total", pretaxTotal)
                .put("total", total)
                .put("tax_payable", taxPayable)
                .put("pretax_freight_total", pretaxFreightTotal)
                .put("freight_total", freightTotal)
                .put("tax_payable_freight_tota", taxPayableFreightTotal)
                .put("pretax_amount", pretaxAmount)
                .put("amount", amount)
                .build();


    }


    @Path("getOrderInfo")
    @POST
    @Operation(summary = "购物车-获取订单创建数据", tags = CUSTOM_SERVICE, description = "")
    public SingleResponse getOrderInfo(Ids ids) {

        if (null == ids.getIds() || ids.getIds().isEmpty()) return SingleResponse.buildFailure("-1","请选择购物车商品！");
        //判断下单是否为寄售下单
        if(StringUtils.isNotBlank(ids.getGoodsSrc()) && ids.getGoodsSrc().equals(GoodsSrcEnum.Vmi.name())){
            return orderService.buildVmiOrder(ids.getIds());
        }else{
            int count = JdbcTemplateUtils.builder(ModelConst.T_CART)
                    .selectField(" count(*) as count ")
                    .in("id", ids.getIds()).queryForObject(Integer.class);

            if (count != ids.getIds().size()) {
                return SingleResponse.buildFailure("-1","购物车商品不存在, 该商品可能已在订单处理中!");
            }
        }
        return builderCustomerOrder(ids.getIds());

    }


    private SingleResponse builderCustomerOrder(List<String> idList) {

        //客户订单 t_order_customer
        Map<String, Object> customerOrder = new HashMap<>();
        //订单数据  t_order_goods
        Map<String, Object> orderGoods;
        //商品来源
        CartSrcEnum cartSrcEnum;
        //商品 t_goods_purchase
        Map<String, Object> goods;
        //订单关系 t_order_goods_relation
        Map<String, Object> or;
        //供应商钉单 t_order_vendor
        Map<String, Object> vendorOrder;

        Map<String, Map<String, Object>> vendorOrdersMap = new HashMap<>();

        //购物车数据 t_cart
        List<Map<String, Object>> cartlist = JdbcTemplateUtils.builder(ModelConst.T_CART)
                .selectField(" * ")
                .in("id", idList)
                .queryForList();


        if (cartlist.isEmpty()) {
            return SingleResponse.buildFailure("-1", "购物车数据不存在");
        } else {
            customerOrder.put("customer_id", JSON.parse((String) cartlist.get(0).get("customer_organization_id")));
        }

        //下单人
        SelectorFormat currentUser = bOValidatedAndFormatService.getCurrentUser();

        // 询价单
        Map inquiry;
        //todo 账单周期（天）通过组织配置表获取的, 目前没有
        Integer ap = 100;
        for (Map<String, Object> cart : cartlist) {
            String goodsId = (String) cart.get("goods_id");
            BigDecimal num = (BigDecimal) cart.get("quantity");
            String src = (String) cart.get("goods_src");
            String cartId = (String) cart.get("id");

            orderGoods = new HashMap<>();

            orderGoods.put("num", num);
            orderGoods.put("goods_id", goodsId);
            orderGoods.put("goods_src", src);
            orderGoods.put("client_order_goods_id", "");

            cartSrcEnum = CartSrcEnum.get(src);

            if (cartSrcEnum == CartSrcEnum.SHOP) {

            } else if (cartSrcEnum == CartSrcEnum.EnterpriseMall) {

            } else if (cartSrcEnum == CartSrcEnum.SINGLE || cartSrcEnum == CartSrcEnum.LOOP) {

                goods = BoServiceUtils.loadBo(goodsId, ModelConst.T_GOODS_PURCHASE).getData().getData();


                if (MapUtil.isEmpty(goods) ) {
                    return SingleResponse.buildFailure("-1", String.format("购物车商品【%s】对应的采购目录商品不存在！", cartId));

                }

                if (!Utils.parseObjToBool(goods.get("enabled"))) {
                    return SingleResponse.buildFailure("-1", String.format("购物车商品【%s】对应的采购目录商品已不可采购，请重新选购！", cartId));
                }

                String expire = (String) goods.get("expire");
                if (expire == null) {
                    return SingleResponse.buildFailure("-1", String.format("购物车商品【%s】对应的采购目录商品过期时间数据异常null！", cartId));
                }

                if (DateUtils.parseDate(expire).getTime() < System.currentTimeMillis()) {
                    return SingleResponse.buildFailure("-1", String.format("购物车商品【%s】对应的采购目录商品已过期，请重新询价！", cartId));
                }

                if (null ==goods.get("quotation_goods_id")) {
                    return SingleResponse.buildFailure("-1", String.format("购物车商品【%s】对应的报价商品不存在！", cartId));
                }

                Map quotationGoods = null;
                //循环采购不限制采购权限（子组织也能购买父组织的商品）
                if (cartSrcEnum == CartSrcEnum.SINGLE) {
                    //todo 组织权限功能未完成, 后续逻辑需要补充
                    quotationGoods = JdbcTemplateUtils.builder(AppConst.SOURCING_CENTER,ModelConst.T_QUOTATION_GOODS)
                            .selectField(" * ")
                            .eq("id", goods.get("quotation_goods_id"))
                            .queryForMap();
                } else {
                    quotationGoods = JdbcTemplateUtils.builder(AppConst.SOURCING_CENTER,ModelConst.T_QUOTATION_GOODS)
                            .selectField(" * ")
                            .eq("id", goods.get("quotation_goods_id"))
                            .queryForMap();
                }

                if (null == quotationGoods) {
                    return SingleResponse.buildFailure("-1", String.format("未获取到购物车商品【%s】对应的报价商品，暂无采购权限!", cartId));
                } else {
                    Map<String, Object> inquiryGoods = JdbcTemplateUtils.builder(AppConst.SOURCING_CENTER, ModelConst.T_INQUIRY_GOODS)
                            .selectField(" * ")
                            .eq("id", goods.get("inquiry_goods_id"))
                            .queryForMap();
                    if (!CollectionUtils.isEmpty(inquiryGoods)) {
                        orderGoods.put("demand_goods_id", inquiryGoods.get("demand_goods_id"));
                    }

                }

                //
                inquiry = JdbcTemplateUtils.builder(AppConst.SOURCING_CENTER, ModelConst.T_INQUIRY)
                        .selectField(" * ")
                        .eq("id", goods.get("inquiry_id"))
                        .queryForMap();

                or = new HashMap<>();

                SelectorFormat inquiryMember = Utils.toSelectorFormat(inquiry.get("member_id"));
                inquiryMember = inquiryMember == null ? new SelectorFormat() : inquiryMember;
                or.put("inquiry_member_id", inquiryMember);
                or.put("inquiry_member_name", inquiryMember.getName());
                or.put("inquiry_id", goods.get("inquiry_id"));
                SelectorFormat demand_dept_id = Utils.toSelectorFormat(goods.get("demand_dept_id"));
                String demand_department_name = Utils.getSelectorFormatName(demand_dept_id);
                or.put("demand_department_name", demand_department_name);
                or.put("virtual_quoter_id", quotationGoods.get("platform_quotation_id"));
//                or.put("customer_period_time", inquiry.get("account_period"));
//                or.put("vendor_period_time", inquiry.get("account_period"));
                or.put("region", goods.get("region"));
                or.put("company", goods.get("company"));
                or.put("warehouse", goods.get("warehouse"));
                or.put("delivery_requirements", inquiry.get("logistics_demand"));

                orderGoods.put("cost_center_name", goods.get("cost_center_name"));
                orderGoods.put("demand_dept_id", goods.get("demand_dept_id"));
                orderGoods.put("relation_id", or);

                orderGoods.put("inquiry_id", goods.get("inquiry_id"));
                orderGoods.put("inquiry_member_name", inquiryMember.getName());
                orderGoods.put("demand_department_name", demand_department_name);

                // 订单商品账期取询价单的账期
                orderGoods.put("customer_account_period", inquiry.get("account_period"));
                orderGoods.put("category", Optional.ofNullable(goods.get("catalog")).orElse(""));
                orderGoods.put("brand", goods.get("brand"));
                orderGoods.put("name", goods.get("name"));
                orderGoods.put("model", goods.get("model"));
                orderGoods.put("spec", goods.get("spec"));
                orderGoods.put("sku", Optional.ofNullable(goods.get("customer_sku")).orElse(""));
                orderGoods.put("bar_code", Optional.ofNullable(goods.get("bar_code")).orElse(""));
                orderGoods.put("golden_tax", Optional.ofNullable(goods.get("golden_tax")).orElse(""));
                orderGoods.put("unspsc", Optional.ofNullable(goods.get("unspsc")).orElse(""));
                orderGoods.put("images", Optional.ofNullable(goods.get("images")).orElse(""));
                orderGoods.put("description", Optional.ofNullable(goods.get("description")).orElse(""));
                orderGoods.put("unit", goods.get("unit"));
                orderGoods.put("package_unit", goods.get("package_unit"));
                orderGoods.put("package_quantity", goods.get("package_num"));
                orderGoods.put("delivery", goods.get("delivery"));
                orderGoods.put("clarify_tips", Optional.ofNullable(goods.get("clarify_tips")).orElse(""));
                orderGoods.put("remark_message", Optional.ofNullable(quotationGoods.get("remark_message")).orElse(""));

                orderGoods.put("tax_rate_freight", goods.get("tax_rate_freight"));
                orderGoods.put("tax_rate", cart.get("tax_rate"));
                orderGoods.put("pretax_price", cart.get("pretax_price"));
                orderGoods.put("pretax_freight", cart.get("pretax_freight"));
                orderGoods.put("pretax_total", cart.get("pretax_total"));
                orderGoods.put("freight_total", cart.get("freight_total"));
                orderGoods.put("pretax_amount", cart.get("pretax_amount"));

                orderGoods.put("price", cart.get("price"));
                orderGoods.put("freight", cart.get("freight"));
                orderGoods.put("total", cart.get("total"));
                orderGoods.put("amount", cart.get("amount"));
                orderGoods.put("region", goods.get("region"));
                orderGoods.put("company", goods.get("company"));
                orderGoods.put("warehouse", goods.get("warehouse"));
                //增加下单人
                orderGoods.put("place_order_user_id", currentUser);
                orderGoods.put("place_order_fullname", currentUser.getName());


            }else {
                return SingleResponse.buildFailure("-1","购物车商品来源错误");
            }

            //供应商

            SelectorFormat vendorBo = JsonUtils.toObject((String)cart.get("vendor_organization_id"),SelectorFormat.class);


            if (vendorOrdersMap.containsKey(vendorBo.getId())) {
                vendorOrder = vendorOrdersMap.get(vendorBo.getId());

                compute(vendorOrder, cart);

            }else{
                vendorOrder = new HashMap<>();
                vendorOrder.put("vendor_id",vendorBo);
                vendorOrdersMap.put(vendorBo.getId(), vendorOrder);
                vendorOrder.put("order_vendor_status", OrderVendorStatusEnum.UpcomingPayment.name());
                vendorOrder.put("account_period",ap);
                vendorOrder.put("organization_name",vendorBo.getName());
                vendorOrder.put("memo","");

                vendorOrder.put("pretax_freight", Optional.ofNullable(cart.get("pretax_freight")).orElse(BigDecimal.ZERO));
                vendorOrder.put("freight",  Optional.ofNullable(cart.get("freight")).orElse(BigDecimal.ZERO));
                vendorOrder.put("tax_payable",  Optional.ofNullable(cart.get("tax_payable")).orElse(BigDecimal.ZERO));
                vendorOrder.put("tax_payable_freight",  Optional.ofNullable(cart.get("tax_payable_freight")).orElse(BigDecimal.ZERO));
                vendorOrder.put("pretax_total", Optional.ofNullable(cart.get("pretax_total")).orElse(BigDecimal.ZERO));
                vendorOrder.put("total", Optional.ofNullable(cart.get("total")).orElse(BigDecimal.ZERO));
                vendorOrder.put("pretax_amount", Optional.ofNullable(cart.get("pretax_amount")).orElse(BigDecimal.ZERO));
                vendorOrder.put("amount", Optional.ofNullable(cart.get("amount")).orElse(BigDecimal.ZERO));

                vendorOrder.put("orderGoodsList", new ArrayList<>());
            }
            orderGoods.put("vendor_organization_id", vendorBo);

            //订单商品列表
            List<Map<String,Object>> orderGoodsList = (List<Map<String, Object>>) vendorOrder.get("orderGoodsList");
            orderGoodsList.add(orderGoods);


        }

        customerOrder.put("cart_id",idList);

        List<Map<String,Object>> vendorOrders = vendorOrdersMap.entrySet().stream().map(Map.Entry::getValue).collect(Collectors.toList());

        customerOrder.put("erp_po", "");
        customerOrder.put("cartIds", idList.size());

        customerOrder.put("pretax_freight", BigDecimal.ZERO);
        customerOrder.put("freight", BigDecimal.ZERO);
        customerOrder.put("tax_payable", BigDecimal.ZERO);
        customerOrder.put("tax_payable_freight", BigDecimal.ZERO);
        customerOrder.put("pretax_total", BigDecimal.ZERO);
        customerOrder.put("total", BigDecimal.ZERO);
        customerOrder.put("pretax_amount", BigDecimal.ZERO);
        customerOrder.put("amount", BigDecimal.ZERO);


        customerOrder.put("vendorOrders",vendorOrders);


        vendorOrders.forEach(vendor->{

            compute(customerOrder, vendor);
        });


        List<Map<String, Object>> adderssList = JdbcTemplateUtils.builder(AppConst.PERSONAL_CENTER, ModelConst.T_MEMBER_DELIVER_ADDRESS)
                .selectField(" * ")
                .eq("JSON_UNQUOTE(member_id -> '$.id')", RequestContext.getCorpLoginId())
                .queryForList();

        if (!adderssList.isEmpty()) {
            Map<String, Object> adderss = adderssList.get(0);
            AddrFormat addrFormat = Utils.getAddrFormat(adderss.get("area_id"));
            customerOrder.put("receiver", adderss.get("receiver_name"));
            customerOrder.put("phone", adderss.get("mobile"));
            customerOrder.put("address", Utils.getAddrFormatAddr(addrFormat) + adderss.get("address"));
            customerOrder.put("postal", adderss.get("post"));
        }else{
            customerOrder.put("receiver", "");
            customerOrder.put("phone", "");
            customerOrder.put("address", "");
            customerOrder.put("postal", "");
        }



        return SingleResponse.of(customerOrder);
    }

    private void compute(final Map<String, Object> sourceMap, final Map<String, Object> map) {
        String[] key = {"pretax_freight", "freight", "tax_payable", "tax_payable_freight",
                "pretax_total", "total", "pretax_amount", "amount"};

        for (String a : key) {
            this.bigDecimalAccumulation(sourceMap, map, a);
        }
    }

    private void bigDecimalAccumulation(final Map<String, Object> sourceMap, final Map<String, Object> map, String key) {
        if (StringUtils.isEmpty(key)) {
            return;
        }
        BigDecimal val1 = (BigDecimal) Optional.ofNullable(map.get(key)).orElse(BigDecimal.ZERO);
        BigDecimal val2 = (BigDecimal) Optional.ofNullable(sourceMap.get(key)).orElse(BigDecimal.ZERO);
        sourceMap.put(key, BigDecimalUtils.add(val2, val1));
    }

    @Path("demandGoodsToInquiry")
    @POST
    @Operation(summary = "获取匹配需求数据", tags = CUSTOM_SERVICE, description = "")
    public SingleResponse demandGoodsToInquiry(DemandGoodsToInquiryDto dto) {

        String sqltable = " from demandpool.i_demandpool_t_demand_goods  dg " +
                "LEFT JOIN demandpool.i_demandpool_t_demand_pool dp on dg.demand_pool_id = dp.id ";
        String sqlField = " dg.id,dp.member_id,dp.member_fullname,dg.`name`,dg.brand,dg.model,dp.cost_center_name ";

        StringBuilder sqlWhere = new StringBuilder(" where 1=1 ");


        StringBuilder sqlData = new StringBuilder("select ").append(sqlField).append(sqltable);
        StringBuilder sqlCount = new StringBuilder("select count(1) as count ").append(sqltable);
        Map<String, Object> param = new HashMap<>();

        if (StringUtils.isNotEmpty(dto.getId())) {
            param.put("id", dto.getId());
            sqlWhere.append("and dg.id = :id ");
        }
        if (StringUtils.isNotEmpty(dto.getMember_id())) {
            param.put("member_id", Utils.likeVal(dto.getMember_id()));
            sqlWhere.append("and dp.member_id like :member_id ");
        }
        if (StringUtils.isNotEmpty(dto.getName())) {
            param.put("name", dto.getName());
            sqlWhere.append(" and dg.name = :name ");
        }
        if (StringUtils.isNotEmpty(dto.getBrand())) {
            param.put("brand", dto.getBrand());
            sqlWhere.append("and dg.brand = :brand  ");
        }
        if (StringUtils.isNotEmpty(dto.getModel())) {
            param.put("model", dto.getModel());
            sqlWhere.append("and dg.model = :model ");
        }
        if (StringUtils.isNotEmpty(dto.getCost_center_name())) {
            param.put("cost_center_name", dto.getCost_center_name());
            sqlWhere.append("and dp.cost_center_name = :cost_center_name ");
        }

        //todo  需要补充权限相关条件

        sqlData.append(sqlWhere).append(dto.limit());
        sqlCount.append(sqlWhere);

        Integer total = jdbcTemplate.queryForObject(sqlCount.toString(), param, Integer.class);

        List<Map<String, Object>> list = jdbcTemplate.queryForList(sqlData.toString(), param);

        return SingleResponse.of(MapBuilder.create(new HashMap<>())
                .put("total", total)
                .put("list", list)
                .build());
    }


}
